//建立连接
let socket = io.connect('http://localhost:7000');

//获取DOM元素
let message = document.getElementById('message'),
    username = document.getElementById('username'),
    feedbackArea = document.getElementById('feedbackArea'),
    sendBtn = document.getElementById('sendBtn'),
    outputArea = document.getElementById('outputArea');

sendBtn.addEventListener('click', () => {
    if (!username.value) {
        alert("请输入用户名");
        return;
    } else if (!message.value) {
        alert("请输入要发送的内容");
        return;
    }
    socket.emit('chat', {
        message: message.value,
        username: username.value
    });
})

//message输入框输入中文时触发
message.addEventListener('compositionstart', () => {
    socket.emit('typing', username.value); //给该socket的客户端发送消息（emit）
})

//监听事件
socket.on('chat', (data) => {
    message.value = "";
    feedbackArea.innerHTML = "";
    outputArea.innerHTML += '<p><strong>' + data.username + '：</strong>' + data.message + '</p>';
})

socket.on('typing', (data) => {
    console.log('typing', data);
    feedbackArea.innerHTML = '<p class="typingTips"><em>' + data + '正在输入中...</em></p>'
})